package cc.mrbird.febs.business.service.impl;

import cc.mrbird.febs.business.dao.StoreMapper;
import cc.mrbird.febs.business.domain.Store;
import cc.mrbird.febs.business.service.StoreService;
import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.utils.SortUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("storeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    @Override
    public IPage<Store> findStores(Store storeFile, QueryRequest request) {
        try {
            LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();

            if (StringUtils.isNotBlank(storeFile.getStoreName())) {
                queryWrapper.eq(Store::getStoreName, storeFile.getStoreName());
            }
            if (StringUtils.isNotBlank(storeFile.getStoreType())) {
                queryWrapper.eq(Store::getStoreType, storeFile.getStoreType());
            }
            if (storeFile.getCommId() != null) {
                queryWrapper.eq(Store::getCommId, storeFile.getCommId());
            }
            Page<Store> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page,queryWrapper);
        } catch (Exception e) {
            log.error("获取店铺信息失败", e);
            return null;
        }
    }

    @Override
    public Store findByName(String storeFileName) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Store>().eq(Store::getStoreName, storeFileName));
    }

    @Override
    public void createStore(Store storeFile) {
        storeFile.setCreateTime(new Date());
        this.save(storeFile);
    }

    @Override
    public void deleteStores(String[] storeFileIds) throws Exception {
        List<String> list = Arrays.asList(storeFileIds);
        baseMapper.deleteBatchIds(list);
    }

    @Override
    public void updateStore(Store storeFile) throws Exception {
        storeFile.setModifyTime(new Date());
        baseMapper.updateById(storeFile);
    }

}
